package com.example.demo.test;

import java.util.ArrayList;
import java.util.List;

public class Bus implements Subject{
    /**
     * 车速
     */
    private Integer speed;
    /**
     * 设备集合
     */
    private List<Observer> facilityList = new ArrayList<>();
    @Override
    public void attach(Observer facility) {
        facilityList.add(facility);
    }

    @Override
    public void detach(Observer facility) {
        facilityList.remove(facility);
    }

    @Override
    public void notifyFacility() {
        for (Observer facility : facilityList) {
            facility.update();
        }
    }

    public Integer getSpeed() {
        return speed;
    }

    public void setSpeed(Integer speed) {
        this.speed = speed;
    }
}

/**
 * 显示器
 */
class Display implements Observer{
    private Bus bus;
    private Integer speed;

    public Display(Bus bus) {
        this.bus = bus;
    }

    @Override
    public void update() {
        this.speed = bus.getSpeed();
        show();
    }

    @Override
    public void show() {
        System.out.println("显示器: 当前车速 " + speed);
    }
}

/**
 * 警报器
 */
class Siren implements Observer{
    private Bus bus;
    private Integer speed;

    public Siren(Bus bus) {
        this.bus = bus;
    }

    @Override
    public void update() {
        this.speed = bus.getSpeed();
        show();
    }

    @Override
    public void show() {
        if (speed >= 40){
            System.out.println("警报器: 您已超速，请减速行驶！");
        }else {
            System.out.println("警报器: 当前车速正常");
        }
    }
}
interface Subject {
    void attach(Observer facility);

    void detach(Observer facility);

    void notifyFacility();
}

interface Observer {
    void update();

    void show();
}
class Main{
    public static void main(String[] args) {
        Bus bus = new Bus();
        Display display = new Display(bus);
        Siren siren = new Siren(bus);
        bus.attach(display);
        bus.attach(siren);
        //----------------公交车起步，正常速度----------------
        bus.setSpeed(20);
        bus.notifyFacility();
        //----------------公交车超速------------------------
        bus.setSpeed(45);
        bus.notifyFacility();
    }
}

